package configuration

import org.holynite.TiebarSpiderFx.Beans.AppDefinations
import org.holynite.TiebarSpiderFx.Main.SPFxmlLoader
import org.springframework.context.ApplicationContext
import org.springframework.context.annotation.*
import org.springframework.core.io.ClassPathResource
import utils.LogFactory

import javax.xml.bind.JAXBContext
import java.util.logging.Logger

/**
 * Created by midnite on 14/11/27.
 */
@Configuration
@ComponentScan(
		basePackages = [
		        'org.holynite.TiebarSpiderFx'
		]
)
@EnableAspectJAutoProxy
class ApplicationContextConfiguration {

	static final Logger log = LogFactory.getLogger(ApplicationContextConfiguration)
	static ApplicationContext ctx

	static ApplicationContext getAppContext() {
		if (!ctx) InitContext()
		ctx
	}

	static void InitContext() {
		ctx = new AnnotationConfigApplicationContext(ApplicationContextConfiguration)
	}

	@Bean(name = "defaults")
	AppDefinations getAppDefaults() {
		try {
			def unmarshaller = JAXBContext.newInstance(AppDefinations).createUnmarshaller()
			unmarshaller.unmarshal(new ClassPathResource("/configs/defaults.xml").inputStream) as AppDefinations
		} catch (e) {
			log.finer("Default load failed. ${e.message}")
			new AppDefinations()
		}
	}

	@Bean(name = "FxmlLoader")
	SPFxmlLoader initLoader() {
		new SPFxmlLoader()
	}
}
